package com.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.entity.AlipayConfigEnum;
import com.service.AlipayService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName AlipayServiceImpl
 * @Description 支付宝支付业务层实现类
 * @Author Kx
 * @Date 2025/6/3 15:17
 * @Version 1.0
 */
@Service("alipayService")
public class AlipayServiceImpl implements AlipayService {
    private final AlipayClient alipayClient;

    public AlipayServiceImpl(AlipayClient alipayClient) {
        this.alipayClient = alipayClient;
    }

    /**
     * @author: kx
     * @date: 2025/6/3 15:58
     * @param orderNo : 订单编号
     * @param amount : 金额
     * @return java.lang.String
     * @description: 生成支付二维码
    */
    @Override
    public String createOrder(String orderNo, String amount) {
        try {
            //创建了一个支付宝请求对象，用于设置回调地址和请求参数
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
            request.setNotifyUrl(AlipayConfigEnum.getInstance().getNotifyUrl());

            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", orderNo);
            bizContent.put("total_amount", amount);
            bizContent.put("subject", "订单支付");
            bizContent.put("timeout_express","3m"); // 设置超时时间为3分钟

            //将请求参数转换成json格式保存在请求对象中
            request.setBizContent(new JSONObject(bizContent).toString());

            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            System.err.println("支付宝返回错误码：" + response.getCode());
            System.err.println("错误描述：" + response.getMsg());
            System.err.println("子错误码：" + response.getSubCode());
            System.err.println("子错误描述：" + response.getSubMsg());

            if (response.isSuccess()) {
                return response.getQrCode(); // 返回二维码内容（URL），前端可生成图片
            } else {
                throw new RuntimeException("生成二维码失败: " + response.getSubMsg());
            }
        } catch (Exception e) {
            //打印完整异常堆栈
            e.printStackTrace(); //  关键！打印异常堆栈
            System.err.println("异常消息：" + e.getMessage()); // 输出异常简要信息
            if (e.getCause() != null) {
                System.err.println("根本原因：" + e.getCause().getMessage()); //  查看底层异常
            }

            throw new RuntimeException("调用支付宝API异常", e);
        }
    }
}
